import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
	StyleSheet, Text, View, TouchableOpacity,
	Image, PixelRatio, FlatList, Alert
} from "react-native";
import { API, API_GENERATE } from '../../config/api';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../config/global';
import { style } from '../../theme/style';
import HTTP from '../../utils/http';
import ToastUtil from '../../utils/toast';
import { RefuseModal } from '../../component/ModalVerifylComponent.js';
import { Common } from '../../component/common/Common';
import { OrderCommon } from '../order-new/_common/common';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import { NewAccountHome } from '../../components/common/newAccountHome';
import { ProgressModal } from '../../components/common/ProgressModal';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../imgs/sanjiao3.png')

export class RebateListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '客户返利',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			companyIndex: 0,
			status: 'data',
			refreshIcon: false,
			listData: [],
			itemData: {},
			params: {},
			totalPage: '0',
			options: [],
			choice: {},
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
				status: 'data',
				refreshIcon: false,
			},
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1;
		this.pageParams = {
			pageNo: 1,
			pageSize: 10,
		}
	}

	async componentDidMount() {
		await this.init();
		await this.initPage();
	}

	//初始化数据
	init = async () => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let options = await HTTP.POST(API_GENERATE(API.WORKFLOW_LEADER_AUDITCNT), { processDefKeyList: ['process_rebate_apply'] })
		if (options) {
			options.map(item => {
				item.rowCount = item.taskCnt
			})
			this.setState({
				options,
				choice: options[this.state.companyIndex] || {}
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	initPage = async () => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.params = {
			pageNo: this.pageParams.pageNo,
			pageSize: this.pageParams.pageSize,
			corpId: this.state.options[this.state.companyIndex].corpId
		}
		let res = await HTTP.POST(API_GENERATE(API.REBARE_LIST), this.params)
		if (res) {
			let responseData = res.rows;
			this.setState({
				listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
				status: responseData.length > 0 ? 'data' : 'empty',
				refreshIcon: false,
				totalPage: res.totalPage,

			})
			this.pageParams.pageNo = res.pageNo++;
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	loadMore = () => {
		if (this.state.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	refresh = () => {
		this.pageParams.pageNo = 1;
		if (this.state.totalPage >= this.pageParams.pageNo) {
			this.reload = false;
			this.initPage();
		}
	}

	onErrorRefresh = () => {
		this.initPage();
	}

	goSkipPage = (data) => {
		this.props.navigation.navigate('RebateDetailPage', {
			data,
			callback: () => { this.reloadPage() }
		})
	}

	// 审批
	approve = async () => {
		const { itemData, choice } = this.state;
		if (this.requesting) return;
		this.setState({ showRejectModal: false });
		this.requesting = true;
		let requestParams = {
			businessKey: itemData.businessKey,
			taskId: itemData.taskId,
			formKey: itemData.formKey,
			auditResult: this.auditResult,
			remark: this.remark,
		};
		let text = this.auditResult ? '同意' : '驳回';
		this.setState({ status: 'loading' });
		let res = await HTTP.POST(API_GENERATE(API.REBARE_AUDIT), requestParams);
		this.requesting = false;
		if (res) {
			ToastUtil.showSuccess(`${text}成功`).then(() => {
				this.reloadPage()
			})
		} else {
			this.setState({
				status: 'data'
			})
		}
	}

	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}


	_approvalListItim = (data) => {
		let item = data.item;
		let { rebateMonth } = item
		if (rebateMonth) {
			rebateMonth = rebateMonth.slice(4)
			if (Number(rebateMonth) >= 10) {
				rebateMonth = rebateMonth
			}
			else {
				rebateMonth = rebateMonth.slice(1)
			}
		}
		return (
			<TouchableOpacity style={{
				marginTop: 20 * scale, paddingLeft: 12 * scale,
				paddingRight: 12 * scale,
			}}
				onPress={() => {
					this.goSkipPage(item)
				}}
			>
				<View style={styles.itemWrap}>
					<View style={{ marginBottom: 10 * scale, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
						<Text style={styles.itemLightText}>{item.applyId || '--'}</Text>
						<Image source={arrowIcon} style={styles.arrowIcon} />
					</View>
					<View style={styles.itemBorder}></View>
					<View>
						<View style={styles.itemTypeBox}>
							<View style={styles.itemType}>
								<Text style={styles.itemTypeTitle}>优惠标题：</Text>
							</View>
							<Text style={styles.itemTypeText}>
								{item.rebateName || '--'}
							</Text>
						</View>
						<View style={styles.itemTypeBox}>
							<View style={styles.itemType}>
								<Text style={styles.itemTypeTitle}>返利品类：</Text>
							</View>
							<Text style={styles.itemTypeText}>
								{item.groupItemList && item.groupItemList.map((i, index) => {
									if (index < item.groupItemList.length - 1) {
										return (
											i.groupName + '（' + i.regionNames + '）' + '/'
										)
									}
									else {
										return (
											i.groupName + '（' + i.regionNames + '）'
										)
									}
								})}
							</Text>
						</View>
						<View style={styles.itemTypeBox}>
							<View style={styles.itemType}>
								<Text style={styles.itemTypeTitle}>返利执行：</Text>
							</View>
							<Text style={styles.itemTypeText}>
								{rebateMonth + '月'}
							</Text>
						</View>
						<View style={styles.itemTypeBox}>
							<View style={styles.itemType}>
								<Text style={styles.itemTypeTitle}>申请人：</Text>
							</View>
							<Text style={styles.itemTypeText}>
								{item.submitByName}
								{item.staffLineName ? '（' + item.staffLineName + '）' : null}
							</Text>
						</View>
						<View style={styles.itemBorder}></View>
						<View style={styles.itemBottom}>
							<View style={styles.itemDayTime}>
								<Text style={styles.consent} onPress={() => {
									this.auditResult = 1;
									this.remark = '';
									this.setState({
										showRejectModal: true,
										itemData: item,
									})
								}}>同意</Text>
								<Text style={styles.itemdown} onPress={() => {
									if (item) {
										this.auditResult = 0;
										this.remark = '';
										this.setState({
											showRejectModal: true,
											itemData: item,
										})
									} else {
										ToastUtil.showWarning('没有数据')
									}
								}}>驳回</Text>
							</View>
						</View>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	render() {
		let { listData, refreshIcon, status, resAuditcntList, showRejectModal, choice, options, lightBoxData } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={async () => {
					await this.init();
					await this.initPage();
				}} />
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => {
							this.setState({ companyIndex: val }, () => {
								this.pageParams.pageNo = 1;
								this.init();
								this.initPage();
							})
						}}
						options={options}
						choice={choice} />
					: null}
				{
					status == 'data' ? (
						(
							<View style={styles.body}>
								<FlatList
									data={listData}
									renderItem={
										this._approvalListItim
									}
									refreshing={refreshIcon}
									onRefresh={() => { this.refresh() }}
									onEndReachedThreshold={1}
									onEndReached={() => { this.loadMore() }}
								/>
							</View>
						)
					) : (<View style={{ flex: 1 }}>
						<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
					</View>)
				}
				<RefuseModal
					titleText={'审批意见'}
					placeholderText={this.auditResult ? '请输入同意原因' : null}
					propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
					visible={showRejectModal}
					btnPress={(text) => {
						this.remark = text;
						this.approve();
					}}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
				<ProgressModal {...lightBoxData} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	body: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	itemLightText: {
		fontSize: 12 * scale,
		color: '#000000',
		fontWeight: '600',
	},
	itemDayTime: {
		justifyContent: 'flex-end',
		flex: 1,
		flexDirection: 'row'
	},
	itemBottom: {
		justifyContent: 'space-between',
		flexDirection: 'row',
		alignItems: "center",
	},
	consent: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		fontSize: 12 * scale,
		opacity: 1,
		color: '#ffffff',
		alignItems: 'center',
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		// marginRight: 0 * scale,
		flexDirection: 'row',
		backgroundColor: style.color.themeColor,
		overflow: 'hidden'
	},
	itemdown: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
		alignItems: 'center',
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		marginRight: 20 * scale,
		flexDirection: 'row',
		marginLeft: 10 * scale,
	},
	itemWrap: {
		backgroundColor: '#fff',
		width: '100%',
		borderRadius: 8 * scale,
		// paddingLeft: 12 * scale,
		paddingTop: 11 * scale,
		paddingBottom: 14 * scale,
	},
	itemType: {
		width: 70 * scale,
		flexDirection: 'row',
		// alignItems: 'flex-end',
		justifyContent: 'flex-end',
		borderRadius: 4 * scale,
		marginRight: 10 * scale,
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	arrowIcon: {
		width: 8 * scale,
		height: 12 * scale,
		position: 'absolute',
		right: 0,
		top: 2 * scale,
		right: 12 * scale,
	},
	itemTypeBox: {
		flexDirection: 'row',
		marginBottom: 15 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	itemTypeTitle: {
		color: '#030303',
		opacity: 0.61,
		fontSize: 12 * scale,
	},
	itemTypeText: {
		color: '#000000',
		fontSize: 12 * scale,
		fontWeight: '600',
		width: 230 * scale,
	}
})